package excel;

import java.text.DecimalFormat;
import java.util.List;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.Font;

import alList.StuGPA;

public class FormExport {
	public static void exportList(String url, List<StuGPA> stuGPAList) throws Exception {
		String[] fieldStrings = {"StuID", "Name", "Grade", "GPA", "Credit"};

		HSSFWorkbook wb = new HSSFWorkbook();  
        HSSFSheet sheet = wb.createSheet("sheet1");  
        HSSFCellStyle style = wb.createCellStyle(); 
        style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        Font font = wb.createFont();   
        font.setFontHeightInPoints((short)10);   
        font.setFontName("Cambria");   
        style.setFont(font);        
        style.setWrapText(false); 
        
  
        HSSFRow row = sheet.createRow(0); 
        HSSFCell cell;
        for (short i = 0; i < fieldStrings.length; i++)  
        {  
            cell = row.createCell((int)i); 
            cell.setCellStyle(style);  
            cell.setCellValue(fieldStrings[i]);  
        }  
        
        DecimalFormat decimalFormat = new DecimalFormat(".00");
        
        for (int i = 0; i < stuGPAList.size(); i ++) {
        	StuGPA stuGPA = stuGPAList.get(i);
        	row = sheet.createRow(i+1);
			cell = row.createCell(0);
			cell.setCellValue(stuGPA.getStuNum());
			cell = row.createCell(1);
			cell.setCellValue(stuGPA.getStuName());
			cell = row.createCell(2);
			cell.setCellValue(decimalFormat.format(stuGPA.getStuGrade()));
			cell = row.createCell(3);
			cell.setCellValue(decimalFormat.format(stuGPA.getStuGPA()));
			cell = row.createCell(4);
			cell.setCellValue(stuGPA.getStuCredit());
			
        }
        
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        try {
			wb.write(os);
		} catch (IOException e) {
			System.out.print("Output failed");
			e.printStackTrace();
		}
        
        byte[] content = os.toByteArray();
        File file = new File(url);
        OutputStream fos = null;
        
		fos = new FileOutputStream(file);
		fos.write(content);
		wb.close();
		os.close();
		fos.close();

	}
}
